/*
 * @Author: szx
 * @Date: 2023-03-27 19:09:13
 * @LastEditTime: 2023-03-28 15:11:02
 * @Description: 
 * @FilePath: \learn\fullstackopen\part1\part1\src\App.js
 */
import { useState, useEffect } from 'react'
import axios from 'axios';
import Filter from './components/Filter'
import PersonForm from './components/PersonForm'
import Persons from './components/Persons'


const App = () => {
  const [persons, setPersons] = useState([])
  const [newName, setNewName] = useState('')
  const [newNumber, setNewNumber] = useState('')
  const [filter, setFilter] = useState('')

  useEffect(() => {
    axios
      .get('http://localhost:3001/persons')
      .then(response => {
        console.log('promise fulfilled')
        setPersons(response.data)
      })
  }, []);

  const addPerson = (event) => {
    event.preventDefault();
    const index = persons.findIndex((person) => person.name === newName)
    if (index == -1)
      setPersons(persons.concat({ name: newName, number: newNumber, id: persons.length + 1 }))
    else alert(`${newName} is already added to phonebook`)
  }

  const handleNameChange = (event) => {
    setNewName(event.target.value)
  }
  const handleNumberChange = (event) => {
    setNewNumber(event.target.value)
  }
  const handleFilterChange = (event) => {
    setFilter(event.target.value)
  }
  const filterPerson = filter === '' ? persons : persons.filter((person) =>
    person.name.toLowerCase().startsWith(filter.toLowerCase())
  )

  return (
    <div>
      <h2>Phonebook</h2>
      <Filter filter={filter} handleFilter={handleFilterChange} />

      <h3>Add a new</h3>
      <PersonForm addPerson={addPerson} newName={newName} handleNameChange={handleNameChange} newNumber={newNumber} handleNumberChange={handleNumberChange} />

      <h3>Numbers</h3>
      <Persons persons={filterPerson} />
    </div>
  )
}

export default App